package org.jiuling.network.tools.request.http.model;

import com.alibaba.fastjson2.JSON;
import org.jiuling.network.tools.request.http.exception.HttpRequestRuntimeException;
import org.jiuling.network.tools.request.http.model.base.HttpRequestDataBase;

/**
 * Http请求体
 * @author 紫灵
 * @date 2024年02月20日 17时47分30秒
 */
public class HttpRequestBody extends HttpRequestDataBase {

    /** 请求内容 */
    private String body;
    /** 请求内容类型 */
    private HttpRequestBodyType httpRequestBodyType;

    public static HttpRequestHeader builder(){
        return new HttpRequestHeader();
    }

    /**
     * 获取内容
     * @return 内容
     */
    public String getBody(){
        switch (httpRequestBodyType){
            case STRING:
                return this.body;
            case MAP:
                return JSON.toJSONString(this);
            case NULL:
                return null;
            default:
                throw new HttpRequestRuntimeException("未知请求内容类型！");
        }
    }

    /**
     * 添加请求内容
     * @param body 请求内容
     * @return 请求内容
     */
    public HttpRequestBody add(String body){
        this.add(body,false);
        return this;
    }

    /**
     * 添加请求内容
     * @param body 请求内容
     * @param isSuperaddition 是否追加参数
     * @return 请求内容
     */
    public HttpRequestBody add(String body,boolean isSuperaddition){
        if(!HttpRequestBodyType.STRING.equals(httpRequestBodyType) && !HttpRequestBodyType.NULL.equals(httpRequestBodyType)){
            throw new HttpRequestRuntimeException("请求内容类型为Map类型，无法设置String类型请求内容");
        }
        this.httpRequestBodyType = HttpRequestBodyType.STRING;
        if(isSuperaddition){
            this.body = this.body + body;
        }else {
            this.body = body;
        }
        return this;
    }

    @Override
    public HttpRequestDataBase add(String key, Object value) {
        return this.add(key,value,false);
    }

    @Override
    public HttpRequestDataBase add(String key, Object value, boolean isSuperaddition) {
        if(!HttpRequestBodyType.MAP.equals(httpRequestBodyType) && !HttpRequestBodyType.NULL.equals(httpRequestBodyType)){
            throw new HttpRequestRuntimeException("请求内容类型为String类型，无法设置Map类型请求内容");
        }
        this.httpRequestBodyType = HttpRequestBodyType.MAP;
        return super.add(key, value, isSuperaddition);
    }

    enum HttpRequestBodyType{
        /** 空类型 */
        NULL,
        /** 字符串类型 */
        STRING,
        /** Map集合类类型 */
        MAP;

        HttpRequestBodyType() {}
    }

}

